import React, { Component } from 'react';

import {
    View,
    Text,
    TextInput,
    TouchableOpacity,
} from 'react-native';

import { reg_phoneStyle as styles } from '../../../../styles';
import Icon from 'react-native-vector-icons/Ionicons';

import { AddemailAction, SelemailAction } from '../../../actions/register'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { myAlert } from '../../../util/compatible';
import stirageUtil from '../../../util/AsyncStorageUtil'
import { NavigationActions } from 'react-navigation';
import { header, header2, header3 } from '../../../util/fetch'

var Dimensions = require('Dimensions');
var width = Dimensions.get('window').width;          //获取屏幕宽度


class Register_email extends Component {
    email = false;
    idcode = false;
    password = false;

    constructor(props) {
        super(props);
        this.state = ({
            //登录按钮是否可用
            isOk: false,
            //验证码是否可用
            isOkIdcode: false,
            //是否等待
            isloading: false,
            show: true
        });
    }

    goIdcode() {
        const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        let a = 0;
        if (this.props.type == 1) {
            a = 1;
        }
        if (reg.test(this.refs.email._lastNativeText)) {
            if (this.state.isOkIdcode) {
                this.setState({ isloading: true, isOkIdcode: false });
                this.props.actions.AddemailAction({
                    email: this.refs.email._lastNativeText,
                    type: a
                });
            }
        } else {
            myAlert('邮箱格式错误');
            this.setState({ isOkIdcode: false });
        }
    }

    goYz() {
        const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if (reg.test(this.refs.email._lastNativeText)) {
            if (this.state.isOk) {
                this.setState({ isloading: true, isOk: false });
                this.props.actions.SelemailAction({
                    email: this.refs.email._lastNativeText,
                    idcode: this.refs.idcode._lastNativeText,
                    password: this.refs.password._lastNativeText
                });
            }
        } else {
            myAlert('邮箱格式错误');
            this.setState({ isOkIdcode: false });
        }
    }

    isOKE(val) {
        if (val.length > 6) {
            this.email = true;
        } else {
            this.email = false;
        }
        this.isOkIdcode();
    }

    isOkIdcode() {
        if (this.email) {
            this.setState({ isOkIdcode: true });
        } else {
            this.setState({ isOkIdcode: false });
        }
    }

    isOk() {
        if (this.idcode && this.email && this.password) {
            this.setState({ isOk: true });
        } else {
            this.setState({ isOk: false });
        }
    }

    isOKCode(val) {
        if (val.length > 3) {
            this.idcode = true;
        } else {
            this.idcode = false;
        }
        this.isOk();
    }

    isOKP(val) {
        if (val.length > 5) {
            this.password = true;
        } else {
            this.password = false;
        }
        this.isOk();
    }

    componentWillReceiveProps(nextProps) {
        const { data } = nextProps.msg
        if (data.msg != "") {
            //登录成功
            if (data.msg == "ok") {
                myAlert('注册成功');
                //保存token
                stirageUtil.save("userType", data.userType).then(() => {
                    //保存token
                    stirageUtil.save("accountToken", data.token).then(() => {
                        header.accessToken = data.token
                        header2.accessToken = data.token
                        header3.accessToken = data.token
                        //跳转页面
                        this.passing();
                    });
                })
            } else {
                //失败弹出消息
                myAlert(data.msg);
            }
            this.setState({ isOk: false, isOkIdcode: false, isloading: false })
        }
    }

    passing() {
        resetAction = NavigationActions.reset({
            index: 0,
            actions: [
                NavigationActions.navigate({ routeName: 'App' })//要跳转到的页面名字
            ]
        });
        this.props.navigation.dispatch(resetAction);
    }

    _onPress() {
        this.refs.password.blur();
    }

    render() {
        return (
            <View style={styles.reg_phone}>
                <View style={styles.input1}>
                    <Icon
                        name={'md-mail'}
                        size={20}
                        color={'#ffffff'} style={styles.s_i} />
                    <TextInput
                        style={[styles.inputin, { width: width * 0.85 }]}
                        placeholder="请输入邮箱"
                        ref="email"
                        underlineColorAndroid="transparent"
                        onChangeText={this.isOKE.bind(this)}
                    />
                    <View style={styles.inputa}>
                        <TouchableOpacity
                            activeOpacity={1}
                            style={
                                this.state.isOkIdcode ?
                                    [styles.buttonsmall, {
                                        elevation: 5,
                                        shadowColor: 'black',
                                        shadowOpacity: 1,
                                        shadowRadius: 5
                                    }]
                                    :
                                    [styles.buttonsmall, {
                                        elevation: 5,
                                        shadowColor: 'black',
                                        shadowOpacity: 1,
                                        shadowRadius: 5,
                                        backgroundColor: "#aeaeae"
                                    }]
                            }
                            underlayColor={this.state.isOkIdcode ? "#3D9CCC" : "#aeaeae"}
                            onPress={this.goIdcode.bind(this)}
                        >
                            <Text style={[styles.button2]}>
                                {this.state.isloading ? "等  待" : "获取验证码"}
                            </Text>
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={styles.input12}>
                    <Icon
                        name={'md-text'}
                        size={22}
                        color={'#ffffff'} style={styles.s_i} />
                    <TextInput style={[styles.inputin2, { width: width * 0.85 }]}
                        placeholder="请输入收到的验证码"
                        ref="idcode"
                        underlineColorAndroid="transparent"
                        onChangeText={this.isOKCode.bind(this)}
                    />
                </View>

                <View style={styles.input12}>
                    <Icon
                        name={'md-lock'}
                        size={24}
                        color={'#ffffff'} style={styles.s_i} />
                    <TextInput
                        style={[styles.inputin3, { width: width * 0.85 }]} ref="password"
                        placeholder="密码（6-16位字母、数字）"
                        password={true}
                        //输入为密码隐藏样式
                        secureTextEntry={this.state.show}
                        clearButtonMode="always"
                        underlineColorAndroid="transparent"
                        onChangeText={this.isOKP.bind(this)}
                    />

                    <TouchableOpacity style={styles.look} activeOpacity={1}
                        onPressIn={() => { [this.setState({ show: !this.state.show }), this._onPress()] }}
                        onPressOut={() => { this.setState({ show: !this.state.show }) }}>
                        <Icon
                            name={'md-eye'}
                            size={22}
                            color={'#ffffff'} />
                    </TouchableOpacity>

                </View>

                <TouchableOpacity
                    activeOpacity={1}
                    style={
                        this.state.isOk ?
                            [styles.buttonall, {
                                width: width * 0.85, elevation: 3,
                                shadowColor: 'black',
                                shadowOpacity: 1,
                                shadowRadius: 5,
                                marginBottom: 5
                            }]
                            :
                            [styles.buttonall, {
                                width: width * 0.85, elevation: 3,
                                shadowColor: 'black',
                                shadowOpacity: 1,
                                shadowRadius: 5,
                                backgroundColor: "#aeaeae",
                                marginBottom: 5
                            }]}
                    underlayColor={this.state.isOk ? "#3D9CCC" : "#aeaeae"}
                    onPress={this.goYz.bind(this)}
                >
                    <Text style={styles.button1}>
                        {this.state.isloading ? "等  待" : "注  册"}
                    </Text>
                </TouchableOpacity>
            </View>

        )
    }
}

//组合action
var actions = {
    AddemailAction,
    SelemailAction
}
//连接state到props
const mapStateToProps = state => {
    return {
        msg: state.AddemailReducer
    }
}
//连接action
const mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators(actions, dispatch)
    }
}
//导出组合好的组件(组合后状态改变重新渲染组合组件的页面)
export default connect(
    mapStateToProps, mapDispatchToProps
)(Register_email);